import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

import 'source/_2_gesture.dart';

class GestureTest extends StatefulWidget {
  const GestureTest({super.key});

  @override
  State<GestureTest> createState() => _GestureTestState();
}

class _GestureTestState extends State<GestureTest> {
  String _operation = "No Gesture detected!"; //保存事件名
  @override
  Widget build(BuildContext context) {
    return Center(
      child: MyGestureDetector(
        child: Container(
          alignment: Alignment.center,
          color: Colors.blue,
          width: 200.0,
          height: 100.0,
          child: Text(
            _operation,
            style: TextStyle(color: Colors.white),
          ),
        ),
        onTap: () => updateText("Tap"), //点击
        onDoubleTap: () => updateText("DoubleTap"), //双击
        onLongPress: () => updateText("LongPress"), //长按
      ),
    );
  }

  void updateText(String text) {
    //更新显示的事件名
    setState(() {
      _operation = text;
    });
  }
}

class _Drag extends StatefulWidget {
  @override
  _DragState createState() => _DragState();
}

class _DragState extends State<_Drag> with SingleTickerProviderStateMixin {
  double _top = 0.0; //距顶部的偏移
  double _left = 0.0; //距左边的偏移

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Positioned(
          top: _top,
          left: _left,
          child: GestureDetector(
            child: CircleAvatar(child: Text("A")),
            //手指按下时会触发此回调
            onPanDown: (DragDownDetails e) {
              //打印手指按下的位置(相对于屏幕)
              print("用户手指按下：${e.globalPosition}");
            },
            //手指滑动时会触发此回调
            onPanUpdate: (DragUpdateDetails e) {
              //用户手指滑动时，更新偏移，重新构建
              setState(() {
                _left += e.delta.dx;
                _top += e.delta.dy;
              });
            },
            onPanEnd: (DragEndDetails e) {
              //打印滑动结束时在x、y轴上的速度
              print(e.velocity);
            },
          ),
        )
      ],
    );
  }
}

class _Scale extends StatefulWidget {
  const _Scale({Key? key}) : super(key: key);

  @override
  _ScaleState createState() => _ScaleState();
}

class _ScaleState extends State<_Scale> {
  double _width = 200.0; //通过修改图片宽度来达到缩放效果

  @override
  Widget build(BuildContext context) {
    return Center(
      child: GestureDetector(
        //指定宽度，高度自适应
        child: Image.asset("images/xiaoyan.jpg", width: _width),
        onScaleUpdate: (ScaleUpdateDetails details) {
          setState(() {
            //缩放倍数在0.8到10倍之间
            _width = 200 * details.scale.clamp(.8, 10.0);
          });
        },
      ),
    );
  }
}

class _GestureRecognizer extends StatefulWidget {
  const _GestureRecognizer({Key? key}) : super(key: key);

  @override
  _GestureRecognizerState createState() => _GestureRecognizerState();
}

class _GestureRecognizerState extends State<_GestureRecognizer> {
  TapGestureRecognizer _tapGestureRecognizer = TapGestureRecognizer();
  bool _toggle = false; //变色开关

  @override
  Widget build(BuildContext context) {
    return Text.rich(
      TextSpan(
        children: [
          TextSpan(text: "你好世界"),
          TextSpan(
            text: "点我变色",
            style: TextStyle(
              fontSize: 30.0,
              color: _toggle ? Colors.blue : Colors.red,
            ),
            recognizer: _tapGestureRecognizer
              ..onTap = () {
                setState(() {
                  _toggle = !_toggle;
                });
              },
          ),
          TextSpan(text: "你好世界"),
        ],
      ),
    );
  }
}

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
            "Lisener只能检测point, 那么怎么检测onTap, doubleTap, longTap之类的呢，这就需要封装Listener, 所以就出现了GestureDetector"),
        Text("1. GestureDetector 内部封装了 Listener，用以识别语义化的手势"),
        Text("1.1 体验动作"),
        GestureTest(),
        SizedBox(height: 10),

        Text("1.2 Drag不能放这里吗？为什么呢？因为要以原点开始计算吗？"),
        // _Drag(),
        SizedBox(height: 10),
        Text("1.3 缩放规模"),
        _Scale(),

        SizedBox(height: 50),
        Text("2. GestureRecognizer"),
        _GestureRecognizer(),
        Text("GestureRecognizer是个抽象类, 各种手势识别都是实现它。"),
        Text(
            "收集手势【Map<Type, GestureRecognizer>? _recognizers】，手势识别【recognizer.addPointer(event)】都得用到它，"),
        SizedBox(height: 50),
        Text("GestureDector实现原理："),
        Text(
            "1. GestureDetector内部将各种动作进行分类收集：Map<Type, GestureRecognizerFactory> gestures"),
        Text(
            "2. 最终内部非常简单，还是封装了Listener(onPointerDown: _handlePointerDown, onPointerPanZoomStart: _handlePointerPanZoomStart, child: widget.child  )")
      ],
    );
  }
}

void main(List<String> args) {
  runApp(MaterialApp(
    home: Scaffold(
      body: Demo(),
      // body: _Drag(),
    ),
  ));
}
